package org.shiwen.week12.answer;

public class Q4 {
    public static double getSum(int n) {
        double sum = 0.0;
        long num = 1;

        for (int i = 1; i <= n; i++) {
            sum = sum + 1.0/(num*i);//请注意，必须要写成1.0/(num*i)，否则两个整数参与运算，会发生精度丢失，导致结果错误
            num = num*i;
        }
        return sum;
    }

    public static double whileSum(int n) {
        double sum = 0.0;
        long num = 1;
        int i = 1;
        while (i <= n) {
            sum = sum + 1.0/(num*i);
            num = num*i;
            i++;
        }
        return sum;
    }
    public static void main(String[] args) {
        System.out.println(getSum(20));
        System.out.println(whileSum(20));
    }
}
